/*S6m9f1+0dTjO4ydGyGkohVRYt704rn82SnAblAOvMVDAnboiyv8ttZCsKBQfIzES*/
import { ajax, toast } from 'nc-lightapp-front';
import constants from '../constants';
import { depmethodUtils } from '../../../facardbase/utils';
let { checkDepmethod } = depmethodUtils;
import ampub from 'ampub';
import fa from 'fa';

const { utils: { msgUtils: { showMessage, showErrorMessageByRes } } } = ampub;
const { fa_components: { ReferLinkage: { referLinkageClear } } } = fa;
const { URL, FIELDS, AREA: { LIST: { GRID_AREA: tableId } }, PAGE_CODE: { LIST: pageCode } } = constants;

// tableAfterEvent.that.props, areaCode, attrcode, queryValue, res.changedrows, indexs, changedRowData, 'MultiLine');
export default function(props, moduleId, field, newValue, changedrows, indexs, record) {
	const { cardTable } = props;
	//效率优化，开启开关
	props.beforeUpdatePage();

	// 折旧方法、使用月限、净残值率(%)
	let linkageData = { pk_category: [ 'pk_depmethod', 'naturemonth', 'salvagerate' ] };

	//变化的行
	let changedIndexes = [];
	if (Array.isArray(indexs)) {
		changedIndexes = [ ...indexs ];
	} else {
		changedIndexes = [ indexs ];
	}

	//从 record 上取当前字段的值数组
	let currValues = [];
	let proIndexes = [];

	let userJson = {
		newasset_flag: 1, //卡片新增标识：资产增加
		current_accbooks: '',
		fromAccbookChange: false,
		editStyle: 'table' //编辑方式：主要用于编辑后事件的多使用部门处理
	};

	let heads = [];
	//这里之所以不取 newValue 参数是由于 他是一个数值 而不是一个对象
	let sendData = {
		attrcode: field,
		newValueList: currValues,
		customValue: userJson,
		userjson: { MultiLine: 'MultiLine' },
		heads,
		grid: {
			pageid: pageCode,
			model: {
				areacode: tableId,
				areaType: 'table',
				rows: []
			}
		}
	};

	let usufructasset_flag = false;

	// 开始循环组织数据
	for (let i = 0; i < changedIndexes.length; i++) {
		let currentIndex = changedIndexes[i];
		//联动处理
		referLinkageClear(
			props,
			field,
			{
				tableId,
				linkageData
			},
			'cardtable',
			moduleId,
			currentIndex
		);

		let currentRecord = record[i];
		let currentChangedRow = changedrows[i];
		let aNewValue = newValue[i];

		//这里改为统一从界面上取数，并更新 assetDataMap
		//多使用部门标记
		let usedep_flag = false;

		//使用部门字段处理
		if (field === 'pk_usedept') {
			//判断是否是多使用部门，需要更新 usedep_flag 的值，
			//单使用部门需要走编辑后 获取资产套号， 多使用部门不需要
			if (currentChangedRow.length && currentChangedRow.length > 1) {
				//多使用部门
				usedep_flag = true;

				cardTable.setValByKeyAndIndex(tableId, currentIndex, 'usedep_flag', { value: usedep_flag });
				cardTable.setValByKeyAndIndex(tableId, currentIndex, 'assetsuit_code', { value: '' });
			} else {
				//单使用部门
				cardTable.setValByKeyAndIndex(tableId, currentIndex, 'usedep_flag', { value: usedep_flag });
			}
		}

		//资产类别需要同时更新交易类型 "pk_transitype", "transi_type"
		if (field === 'pk_category' && aNewValue && aNewValue.values) {
			cardTable.setValByKeyAndIndex(tableId, currentIndex, 'pk_transitype', aNewValue.values.pk_transitype);
			cardTable.setValByKeyAndIndex(tableId, currentIndex, 'transi_type', aNewValue.values.transi_type);
		}

		//交易类型(pk_transitype)更新时同时更新 交易类型编码(transi_type)
		if (field === 'pk_transitype') {
			cardTable.setValByKeyAndIndex(tableId, currentIndex, 'transi_type', { value: aNewValue.refcode });
		}

		//从 state 上获取缓存的数据
		let assetData = this.assetDataMap[currentIndex];
		const currentPkaccbook = this.getMainAccbook(assetData); //选择主账簿
		let mainAccbookData = this.getMainAccbookData(assetData); //选择主账簿数据
		if (!mainAccbookData) {
			//主账簿数据为空表示还未选择【资产类别】
			mainAccbookData = assetData[0];
		}

		//获取当前行的数据,并同步到主账簿中
		let rowData = props.cardTable.getRowsByIndexs(tableId, currentIndex)[0];
		for (let field in mainAccbookData.values) {
			//这里之所以循环赋值 是考虑到字段联动场景
			mainAccbookData.values[field] = rowData.values[field] || mainAccbookData.values[field];
		}

		// 同步财务字段（首次录入）
		this.initSyncAccbook(field, assetData);
		//同步其他账簿的数据
		this.syncDataForCommit(assetData);

		//多使用部门不需要走编辑后事件
		if (usedep_flag) {
			//当前行是多使用部门时进行缓存，用于编辑后恢复
			if (field !== 'pk_usedept') {
				this.usedeptCache[currentIndex] = cardTable.getValByKeyAndIndex(tableId, currentIndex, 'pk_usedept');
			}
			continue;
		}

		//类别字段为空 不走编辑后事件
		let { values: { pk_category } } = currentRecord;
		if (!pk_category || !pk_category.value) {
			continue;
		}

		//开始组装参数
		proIndexes.push(currentIndex);

		heads.push({
			pageid: pageCode,
			model: {
				areacode: tableId,
				areaType: 'table',
				rows: assetData
			}
		});

		// 组装上送
		currValues.push(currentRecord.values[field]);

		let {
			values: { bill_source: { value: bill_source }, usufructasset_flag: { value: usufructasset_flag0 } }
		} = currentRecord;

		// 判断存在使用权资产
		if (usufructasset_flag0) {
			usufructasset_flag = usufructasset_flag0;
		}
	}

	// 卡片为空则不上送
	if (heads.length == 0) {
		return;
	}

	if (usufructasset_flag) {
		const usufructasset_tab = 'usufructasset_tab';
		let usufructasset_tab_rows = [];
		for (let combinationUsufructAsset of this.combinationUsufructAssetDatas) {
			let {
				[usufructasset_tab]: { [usufructasset_tab]: { rows: usufructasset_tab_rows0 } }
			} = combinationUsufructAsset;
			usufructasset_tab_rows = usufructasset_tab_rows.concat(usufructasset_tab_rows0);
		}
		sendData['bodysMap'] = {
			//使用权资产
			[usufructasset_tab]: {
				pageid: pageCode,
				model: {
					areacode: usufructasset_tab,
					rows: usufructasset_tab_rows,
					areaType: 'table'
				}
			}
		};
	}

	// 性能优化，表单和表格统一渲染
	props.updatePage(null, tableId);

	const that = this;

	//不需要关联处理的字段不需要发请求到后台， 包括自定义项
	if (FIELDS.NORELATION_FIELD.includes(field) || field.startsWith(FIELDS.DEF_FIELD)) {
		return;
	}

	ajax({
		url: URL.headafteredit,
		data: sendData,
		async: false,
		success: (res) => {
			let { success, data } = res;
			if (success) {
				afterEventBackHandler.call(that, data, proIndexes);
			}
		},
		error: (err) => {
			for (let i = 0; i < changedIndexes.length; i++) {
				let currentIndex = changedIndexes[i];
				let currentRecord = record[i];
				//清空当前字段值
				let emptyVal = Object.assign(currentRecord.values[field], { display: '', value: '' }); //保持scale为原值
				currentRecord.values[field] = emptyVal;
				cardTable.updateDataByIndexs(tableId, [
					{
						index: currentIndex,
						data: { status: currentRecord.status, values: currentRecord.values }
					}
				]);
			}
			showErrorMessageByRes(props, err);
		}
	});
}

/**
 * 编辑后事件返回处理（除了 财务组织字段 ）
 */
function afterEventBackHandler(data, changedIndexes) {
	const { props, props: { cardTable } } = this;
	//效率优化，开启开关
	props.beforeUpdatePage();
	//后台对当前账簿进行了处理，如果前台已经有选中的账簿，则后台就返回该账簿为当前账簿；
	//如果前台还未选中账簿，则后台设置业务账簿为当前选中账簿
	let { business_accbooks, toUIObject: cards } = data;

	if (!cards) {
		return;
	}

	/* 开始循环 */
	for (let i = 0; i < cards.length; i++) {
		let currentIndex = changedIndexes[i];
		let current_accbook = business_accbooks[i];
		let card = cards[i];
		let { heads } = card;
		let currentAsset = [];
		heads.forEach((head) => {
			if (head[tableId] && head[tableId].rows && head[tableId].rows.length > 0) {
				currentAsset = currentAsset.concat(head[tableId].rows);
			}
		});
		//更新 this.state.assetDataMap 中的值
		this.assetDataMap[currentIndex] = currentAsset;

		let assetvoMap = new Map();
		//判断是否未多使用部门，如果是，从缓存中恢复值
		currentAsset.forEach((row) => {
			let usedep_flag = row.values.usedep_flag.value;
			if (usedep_flag) {
				row.values.pk_usedept = this.usedeptCache[currentIndex];
			}
			//折旧方法 是否停用 判断处理，如果折旧方法已经停用，则清空该字段
			row['values']['pk_depmethod'] = checkDepmethod(row['values']['pk_depmethod'], this.depmethods);

			const { values: { pk_accbook: { value: pk_accbook } } } = row;
			assetvoMap.set(pk_accbook, row);
		});

		//更新表格数据为主账簿的数据
		const businessbookRow = assetvoMap.get(current_accbook);
		cardTable.updateDataByIndexs(tableId, [
			{
				index: currentIndex,
				data: { status: '2', values: businessbookRow.values }
			}
		]);
	}

	// 性能优化，表单和表格统一渲染
	props.updatePage(null, tableId);
}

/*S6m9f1+0dTjO4ydGyGkohVRYt704rn82SnAblAOvMVDAnboiyv8ttZCsKBQfIzES*/